package link;

public class leetCode2_addTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode result = new ListNode(-1);
        ListNode head = result;
        int carry = 0;
        while (l1 != null || l2 != null){
            int a = l1 != null ? l1.val : 0;
            int b = l2 != null ? l2.val : 0;

            int sum = a + b + carry;
            carry = sum / 10;
            int val = sum % 10;
            result.next = new ListNode(val);
            l1 = l1 != null ? l1.next : null;
            l2 = l2 != null ? l2.next : null;
            result = result.next;
        }
        if(carry != 0){
            result.next = new ListNode(carry);
        }

        return head.next;
    }


    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
